package com.example.mr5.mygame.gameQuzhiChess;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.example.mr5.mygame.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Mr.5
 * Date：2016/5/9.
 * Time：09:55
 */
public class GameView extends SurfaceView implements View.OnTouchListener {

    private int[] local = new int[]{1, 1, 0, -1, -1};
    private int[] whiteLostLocal1 = new int[]{-1, -1, 1, 1, 0};
    private int[] whiteLostLocal2 = new int[]{1, 0, 1, -1, -1};
    private int[] blackLostLocal1 = new int[]{1, 1, -1, -1, 0};
    private int[] blackLostLocal2 = new int[]{-1, 0, -1, 1, 1};

    private int WIDTH = 30;
    private Chess[] chesses = new Chess[5];
    private boolean isEnd = false;
    private boolean isFirstStep = true;


    public GameView(Context context) {
        super(context);
        getHolder().addCallback(callback);
        initGameView();

    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(callback);
        initGameView();
    }

    private void initGameView() {
        setZOrderOnTop(true);//设置背景透明
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
        setOnTouchListener(this);
    }

    private void reDraw() {
        Canvas canvas = getHolder().lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        Paint paint = new Paint();
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);    //设置抗锯齿

        paint.setColor(0xFFFF0000);
        paint.setStrokeWidth(10);
        canvas.drawLine(WIDTH / 2, WIDTH / 2, 4.5f * WIDTH, WIDTH / 2, paint);
        canvas.drawLine(WIDTH / 2, WIDTH / 2, WIDTH / 2, 4.5f * WIDTH, paint);
        canvas.drawLine(WIDTH / 2, WIDTH / 2, 4.5f * WIDTH, 4.5f * WIDTH, paint);
        canvas.drawLine(WIDTH / 2, 4.5f * WIDTH, 4.5f * WIDTH, 4.5f * WIDTH, paint);
        canvas.drawLine(WIDTH / 2, 4.5f * WIDTH, 4.5f * WIDTH, WIDTH / 2, paint);

        RectF rectF;
        Bitmap bitmap;
        Chess chess;
        for (int i = 0; i < 5; i++) {
            chess = new Chess();
            chess.setType(local[i]);
            chess.setN(i);
            switch (i) {
                case 0:
                    chess.setXY(0, 0);
                    break;
                case 1:
                    chess.setXY(4, 0);
                    break;
                case 2:
                    chess.setXY(2, 2);
                    break;
                case 3:
                    chess.setXY(0, 4);
                    break;
                case 4:
                    chess.setXY(4, 4);
                    break;
            }


            if (local[i] == Chess.BALCK) {
                bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.black_chess);
                rectF = new RectF(chess.getX() * WIDTH, chess.getY() * WIDTH, (chess.getX() + 1) * WIDTH, (chess.getY() + 1) * WIDTH);
                canvas.drawBitmap(bitmap, null, rectF, null);
            } else if (local[i] == Chess.WHITE) {
                bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.white_chess);
                rectF = new RectF(chess.getX() * WIDTH, chess.getY() * WIDTH, (chess.getX() + 1) * WIDTH, (chess.getY() + 1) * WIDTH);
                canvas.drawBitmap(bitmap, null, rectF, null);
            }

            chesses[i] = chess;

        }
        getHolder().unlockCanvasAndPost(canvas);    //解除锁定，绘制界面
    }

    /**
     * SurfaceHolder.Callback
     * 绘制内容
     */
    SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceDestroyed(SurfaceHolder arg0) {

        }

        @Override
        public void surfaceCreated(SurfaceHolder arg0) {
            reDraw();
        }

        @Override
        public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

        }
    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(!isEnd){
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x, y;
                y = (int) (event.getY() / WIDTH);
                x = (int) (event.getX() / WIDTH);
                if (x + 1 <= 5 && y + 1 <= 5) {
                    if(humenMove(x, y)){
                        isFirstStep = false;
                        if (checkEnd(Chess.WHITE) == Chess.BALCK) {
                            humenWin();
                        } else {
                            computerMove();
                            if (checkEnd(Chess.BALCK) == Chess.WHITE) {
                                humenLost();
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    private boolean humenMove(int x, int y) {
        Chess clickChess = new Chess();
        for (int i = 0; i < 5; i++) {
            if (chesses[i].getX() == x && chesses[i].getY() == y) {
                clickChess.setN(chesses[i].getN());
                clickChess.setXY(x, y);
                clickChess.setType(chesses[i].getType());
            }
        }

        if (clickChess.getType() == Chess.WHITE) {
            switch (clickChess.getN()) {
                case 0:
                    if (local[1] == 0) {
                        local[1] = -1;
                        local[0] = 0;
                        reDraw();
                        return true;
                    } else if (local[2] == 0) {
                        local[2] = -1;
                        local[0] = 0;
                        reDraw();
                        return true;
                    } else if (local[3] == 0) {
                        local[3] = -1;
                        local[0] = 0;
                        reDraw();
                        return true;
                    }
                    break;
                case 1:
                    if (local[0] == 0) {
                        local[0] = -1;
                        local[1] = 0;
                        reDraw();
                        return true;
                    } else if (local[2] == 0) {
                        local[2] = -1;
                        local[1] = 0;
                        reDraw();
                        return true;
                    }
                    break;
                case 2:
                    if (local[0] == 0) {
                        local[0] = -1;
                        local[2] = 0;
                        reDraw();
                        return true;
                    } else if (local[1] == 0) {
                        local[1] = -1;
                        local[2] = 0;
                        reDraw();
                        return true;
                    } else if (local[3] == 0) {
                        local[3] = -1;
                        local[2] = 0;
                        reDraw();
                        return true;
                    } else if (local[4] == 0) {
                        local[4] = -1;
                        local[2] = 0;
                        reDraw();
                        return true;
                    }
                    break;
                case 3:
                    if (local[0] == 0) {
                        local[0] = -1;
                        local[3] = 0;
                        reDraw();
                        return true;
                    } else if (local[2] == 0) {
                        local[2] = -1;
                        local[3] = 0;
                        reDraw();
                        return true;
                    } else if (local[4] == 0) {
                        local[4] = -1;
                        local[3] = 0;
                        reDraw();
                        return true;
                    }
                    break;
                case 4:
                    if(isFirstStep){
                        Toast.makeText(getContext(),"第一步不能移动该白子!请选择另一个白子移动！",Toast.LENGTH_LONG).show();
                        return false;
                    }else {
                        if (local[3] == 0) {
                            local[3] = -1;
                            local[4] = 0;
                            reDraw();
                            return true;
                        } else if (local[2] == 0) {
                            local[2] = -1;
                            local[4] = 0;
                            reDraw();
                            return true;
                        }
                    }
                    break;
            }
        }
        return false;
    }

    private void computerMove() {
        SystemClock.sleep(1000);
        List<Integer> black = new ArrayList<Integer>();
        for (int i = 0; i < 5; i++) {
            if (local[i] == 1) {
                black.add(i);
            }
        }
        int first = (int) (Math.random()*2);
        int second;
        if(first==0){
            second = 1;
        }else second = 0;
        int to1 = blackCanMoveTo(black.get(first));
        if (to1 >= 0) {
            local[black.get(first)] = 0;
            local[to1] = 1;
            reDraw();
        } else {
            int to2 = blackCanMoveTo(black.get(second));
            if (to2 >= 0) {
                local[black.get(second)] = 0;
                local[to2] = 1;
                reDraw();
            }
        }


    }

    private int blackCanMoveTo(int i) {
        switch (i) {
            case 0:
                if ((local[1] == 0)) {
                    return 1;
                } else if (local[2] == 0) {
                    return 2;
                } else if (local[3] == 0) {
                    return 3;
                }
                break;
            case 1:
                if (local[0] == 0) {
                    return 0;
                } else if (local[2] == 0) {
                    return 2;
                }
                break;
            case 2:
                if (local[0] == 0) {
                    return 0;
                } else if (local[1] == 0) {
                    return 1;
                } else if (local[3] == 0) {
                    return 3;
                } else if (local[4] == 0) {
                    return 4;
                }
                break;
            case 3:
                if (local[0] == 0) {
                    return 0;
                } else if (local[2] == 0) {
                    return 2;
                } else if (local[4] == 0) {
                    return 4;
                }
                break;
            case 4:
                if (local[3] == 0) {
                    return 3;
                } else if (local[2] == 0) {
                    return 2;
                }
                break;
        }
        return -1;
    }


    private int checkEnd(int type) {
        if (type == Chess.WHITE) {
            if (Arrays.equals(local, blackLostLocal1) || Arrays.equals(local, blackLostLocal2)) {
                return Chess.BALCK;//电脑输了
            } else return 0;
        } else {
            if (Arrays.equals(local, whiteLostLocal1) || Arrays.equals(local, whiteLostLocal2)) {
                return Chess.WHITE;//人类输了
            } else return 0;
        }
    }

    public void ReStartGame() {
        local = new int[]{1, 1, 0, -1, -1};
        isEnd = false;
        isFirstStep = true;
        reDraw();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        height = MeasureSpec.getSize(heightMeasureSpec);
//        width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(5*WIDTH, 5*WIDTH);  //这里面是原始的大小，需要重新计算可以修改本行
    }

    private void humenWin() {
        isEnd = true;

        new AlertDialog.Builder(getContext()).setTitle("游戏结束")//设置对话框标题
                .setMessage("恭喜您！您战胜了电脑！")//设置显示的内容
                .setPositiveButton("再来一局", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        ReStartGame();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
            }
        }).show();
    }

    private void humenLost() {
        isEnd = true;
        new AlertDialog.Builder(getContext()).setTitle("游戏结束")//设置对话框标题
                .setMessage("很遗憾！您输了！")//设置显示的内容
                .setPositiveButton("再来一局", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        ReStartGame();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
            }
        }).show();
    }
}
